package com.wyl.java.juc_.reentranlock_;

import java.util.concurrent.CountDownLatch;

/**
 * 一句话描述：可重入，通常用于递归；或者一条调用链上可能会重复获取该锁
 *
 * 编写一个线程安全的计数器类，要求支持加一和减一操作，并且可以设置初始值。使用ReentrantLock来实现同步机制。
 * @author 吴宇亮 on 2023/3/28 13:50
 */
public class ReentrantLock01 {

    public static void main(String[] args) throws InterruptedException {
//        problem();
        anwser();
    }

    public static void anwser() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            ReentrantLock01_Counter counter = new ReentrantLock01_Counter();
            counter.setNum(0);

            CountDownLatch countDownLatch = new CountDownLatch(2);
            Thread addtask = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    counter.add();
                }
                countDownLatch.countDown();
            });
            Thread subtask = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    counter.sub();
                }
                countDownLatch.countDown();
            });

            addtask.start();
            subtask.start();
            countDownLatch.await();
            System.out.println(counter.getNum());
        }
    }

    /**
     * 下面是对一个Integer对象进行加一和减一，线程不安全的示例
     */
    public static void problem() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            final Integer[] num = {0};

            CountDownLatch countDownLatch = new CountDownLatch(2);
            Thread addtask = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    num[0]++;
                }
                countDownLatch.countDown();
            });
            Thread subtask = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    num[0]--;
                }
                countDownLatch.countDown();
            });

            addtask.start();
            subtask.start();
            countDownLatch.await();
            System.out.println(num[0]);
        }
    }
}

